<template>
  <a-card :body-style="{ height: 'calc(100vh - 125px)' }">
    <!-- 编辑区域 -->
    <div v-if="showEditForm" class="mb-4">
      <a-card title="编辑政策法规" class="mb-4">
        <template #extra>
          <a-space>
            <a-button @click="cancelEdit">取消</a-button>
            <a-button type="primary" @click="saveEdit">保存</a-button>
          </a-space>
        </template>
        <a-spin
          :loading="editSpinLoading"
          :size="35"
          class="w-[100%]"
          tip="正在处理, 请稍候..."
        >
          <a-form
            ref="editFormRef"
            :model="editForm"
            :rules="editRules"
            auto-label-width
          >
            <div class="flex justify-between" style="flex-wrap: wrap">
              <a-form-item
                class="w-[100%]"
                field="lawsTitle"
                label="法规标题"
                required
              >
                <a-input v-model="editForm.lawsTitle" placeholder="法规标题" />
              </a-form-item>
              <a-form-item
                class="w-[50%]"
                field="publishTime"
                label="发布时间"
                required
              >
                <a-date-picker
                  v-model="editForm.publishTime"
                  class="w-[100%]"
                  disabled-input
                  format="YYYY-MM-DD"
                  placeholder="发布时间"
                />
              </a-form-item>
              <a-form-item
                class="w-[50%]"
                field="status"
                label="法规状态"
                required
              >
                <a-select
                  v-model="editForm.status"
                  allow-clear
                  placeholder="法规状态"
                >
                  <a-option
                    v-for="(d, index) in dicts[proxy.DICT.commonNumberStatus]"
                    :key="index"
                    :label="d.dictValue"
                    :value="d.dictKey"
                  />
                </a-select>
              </a-form-item>
              <a-form-item
                class="w-[100%]"
                field="lawsContent"
                label="法规内容"
              >
                <tinymce-editor
                  ref="editEditorRef"
                  :editorHeight="300"
                  :file-source="fileSource.lindi_laws_content_file.key"
                  @editor-ready="onEditorReady"
                />
              </a-form-item>
              <a-form-item class="w-[100%]" field="lawsFileId" label="相关附件">
                <div class="file-upload-container">
                  <!-- 已有附件展示区域 -->
                  <div
                    v-if="lawsFiles.length > 0"
                    class="existing-files-container mb-4"
                  >
                    <div class="mb-2 flex items-center justify-between">
                      <div class="text-gray-500">
                        <icon-info-circle class="mr-1" /> 已上传附件文件
                      </div>
                    </div>
                    <a-list :bordered="false" :grid="{ gutter: 16, column: 3 }">
                      <a-list-item
                        v-for="(file, index) in lawsFiles"
                        :key="file.uid || index"
                      >
                        <a-card class="file-card" hoverable>
                          <div class="flex items-start">
                            <div class="file-icon mr-3">
                              <a-avatar :size="40" shape="square">
                                <icon-file-pdf
                                  v-if="getFileExtension(file.name) === 'pdf'"
                                />
                                <icon-file-image
                                  v-else-if="
                                    ['jpg', 'png', 'jpeg'].includes(
                                      getFileExtension(file.name)
                                    )
                                  "
                                />
                                <icon-file v-else />
                              </a-avatar>
                            </div>
                            <div class="flex-1 overflow-hidden">
                              <div class="font-medium truncate mb-1">
                                {{ file.fileName || file.name }}
                              </div>
                              <div class="text-gray-500 text-xs mb-1">
                                文件URL：{{
                                  file.fileUrl || file.url || "未知"
                                }}
                              </div>
                              <div class="mt-2">
                                <a-space>
                                  <a-button
                                    size="mini"
                                    type="primary"
                                    @click="downloadAttachmentFile(file)"
                                  >
                                    <template #icon><icon-download /></template>
                                    下载
                                  </a-button>
                                  <a-button
                                    size="mini"
                                    @click="previewAttachmentFile(file)"
                                  >
                                    <template #icon><icon-eye /></template>
                                    预览
                                  </a-button>
                                  <a-button
                                    size="mini"
                                    @click="copyFileUrl(file.url)"
                                  >
                                    <template #icon><icon-copy /></template>
                                    复制URL
                                  </a-button>
                                  <a-button
                                    size="mini"
                                    status="danger"
                                    @click="removeFile(index)"
                                  >
                                    <template #icon><icon-delete /></template>
                                    删除
                                  </a-button>
                                </a-space>
                              </div>
                            </div>
                          </div>
                        </a-card>
                      </a-list-item>
                    </a-list>
                  </div>

                  <upload-file
                    ref="editAttachmentUploadRef"
                    :accept="fileAccept.document"
                    :file-list="lawsFiles"
                    :file-source="fileSource.lindi_laws_content_file.key"
                    :limit="10"
                    :list-type="fileListType.text"
                    :multiple="true"
                    @uploadSuccess="handleUploadSuccess"
                  />
                </div>
              </a-form-item>
            </div>
          </a-form>
        </a-spin>
      </a-card>
    </div>
    <!-- 数据列表 -->
    <a-row
      v-if="!showEditForm"
      class="w-full h-full flex flex-col overflow-x-auto overflow-y-hidden"
    >
      <!-- 查询条件 -->
      <a-row v-if="showSearchRow" class="w-full">
        <a-form
          :model="searchForm"
          label-align="left"
          layout="inline"
          size="small"
        >
          <a-form-item field="lawsTitle" label="法规标题">
            <a-input v-model="searchForm.lawsTitle" placeholder="法规标题" />
          </a-form-item>
          <a-form-item field="status" label="法规状态">
            <a-select
              v-model="searchForm.status"
              allow-clear
              placeholder="法规状态"
            >
              <a-option
                v-for="(d, index) in dicts[proxy.DICT.commonNumberStatus]"
                :key="index"
                :label="d.dictValue"
                :value="d.dictKey"
              />
            </a-select>
          </a-form-item>
        </a-form>
        <a-row class="w-full mt-2" justify="center">
          <a-space>
            <a-button type="primary" @click="getPageList(false)">
              <template #icon>
                <icon-search />
              </template>
              <template #default>查询</template>
            </a-button>
            <a-popconfirm
              :popup-visible="deleteConfirmVisible"
              content="确定删除选中法规吗?"
              type="warning"
              @cancel="onDeleteConfirmCancel"
              @ok="onDeleteConfirmOK"
            >
              <a-button
                status="danger"
                type="primary"
                @click="deleteBtnClick(selectedKeys)"
              >
                <template #icon>
                  <icon-delete />
                </template>
                <template #default>删除</template>
              </a-button>
            </a-popconfirm>
            <a-button @click="getPageList(true)">
              <template #icon>
                <icon-sync />
              </template>
              <template #default>重置</template>
            </a-button>
          </a-space>
        </a-row>
      </a-row>

      <!-- 分割线 -->
      <a-divider v-if="showSearchRow" class="mt-2" />

      <!-- 数据操作区 -->
      <a-row class="w-full flex justify-between">
        <a-space>
          <!-- 添加 -->
          <a-button size="small" type="primary" @click="addBtnClick()">
            <template #icon>
              <icon-plus />
            </template>
            <template #default>添加</template>
          </a-button>
        </a-space>
        <a-space>
          <!-- 刷新 -->
          <a-button shape="circle" size="small" @click="getPageList(false)">
            <template #icon>
              <icon-refresh />
            </template>
          </a-button>
          <!-- 收缩/展开 -->
          <a-button
            shape="circle"
            size="small"
            @click="showSearchRow = !showSearchRow"
          >
            <template #icon>
              <icon-caret-up v-if="showSearchRow" />
              <icon-caret-down v-else />
            </template>
          </a-button>
        </a-space>
      </a-row>

      <!-- 数据展示区 -->
      <a-row class="w-full flex-1 mt-3 overflow-y-auto">
        <a-table
          v-model:selectedKeys="selectedKeys"
          :columns="datatable.columns"
          :data="datatable.records"
          :loading="datatable.loading"
          :pagination="false"
          :row-selection="rowSelection"
          :scroll="{ minWidth: 600, y: '100%' }"
          class="w-[100%]"
          row-key="lawsId"
          table-layout-fixed
        >
          <!-- 法规标题 -->
          <template #lawsTitle="{ record }">
            <a-link icon @click="detailBtnClick(record.lawsId)"
              >{{ record.lawsTitle }}
            </a-link>
          </template>
          <!-- 法规状态 -->
          <template #status="{ record }">
            <dict-convert
              :dict-data="dicts[proxy.DICT.commonNumberStatus]"
              :dict-key="record.status"
            />
          </template>
          <!-- 操作 -->
          <template #operation="{ record }">
            <a-space>
              <a-button
                size="mini"
                type="text"
                @click="editBtnClick(record.lawsId)"
              >
                <template #icon>
                  <icon-edit />
                </template>
                <template #default>编辑</template>
              </a-button>
              <a-popconfirm
                content="确认要删除吗?"
                @ok="deleteBtnOkClick(record.lawsId)"
              >
                <a-button size="mini" status="danger" type="text">
                  <template #icon>
                    <icon-delete />
                  </template>
                  <template #default>删除</template>
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </a-table>
      </a-row>

      <!-- 分页 -->
      <a-row class="w-full flex justify-end mt-2">
        <pagination
          v-if="datatable.total > 0"
          v-model:page-num="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :total="datatable.total"
          @pagination="getPageList(false)"
        />
      </a-row>
    </a-row>

    <a-modal
      v-model:visible="modal.visible"
      :esc-to-close="false"
      :footer="false"
      :mask-closable="false"
      :width="modal.width"
      draggable
    >
      <template #title>{{ modal.title }}</template>
      <component
        :is="modal.component"
        v-if="modal.visible"
        :params="modal.params"
        @cancel="onCancel"
        @ok="onOk"
      />
    </a-modal>
  </a-card>
</template>

<script setup>
import { getCurrentInstance, reactive, ref, shallowRef, onMounted } from "vue";
import { Message } from "@arco-design/web-vue";
import LawsDetail from "./LawsDetail.vue";
import TinymceEditor from "~/components/tinymceEditor/index.vue";
import UploadFile from "~/components/uploadFile/index.vue";
import Pagination from "~/components/pagination/index.vue";
import { fileAccept, fileListType, fileSource } from "~/utils/sys.js";
import {
  addLawsApi,
  deleteLawsByLawsIdApi,
  updateLawsByLawsIdApi,
  getPageLawsListApi,
  getLawsByLawsIdApi,
} from "~/api/lindi/laws.js";
import { deleteFileApi } from "~/api/basic/file.js";

//全局实例
const { proxy } = getCurrentInstance();
//加载字典
const dicts = proxy.LoadDicts([proxy.DICT.commonNumberStatus]);

// 编辑表单相关
const showEditForm = ref(false);
const editSpinLoading = ref(false);
const editFormRef = ref(null);
const editEditorRef = ref(null);
const editAttachmentUploadRef = ref(null);
const currentEditLawsId = ref(null);
const editorReady = ref(false);

// 附件文件列表
const lawsFiles = ref([]);
// 跟踪新上传的文件ID，用于取消时清理
const newUploadedFileIds = ref([]);

// 状态选项 - 使用字典数据
// const statusOptions = [
//   { label: "有效", value: 1, color: "green" },
//   { label: "无效", value: 0, color: "red" },
//   { label: "草案", value: 2, color: "orange" },
// ];

// 编辑表单数据
const editForm = reactive({
  lawsId: null,
  lawsTitle: null,
  lawsContent: null,
  lawsFileId: null,
  publishTime: null,
  status: 1,
});

// 编辑表单校验规则
const editRules = {
  lawsTitle: [
    { required: true, message: "法规标题不能为空", trigger: "submit" },
  ],
  publishTime: [
    { required: true, message: "发布时间不能为空", trigger: "submit" },
  ],
  status: [{ required: true, message: "法规状态不能为空", trigger: "submit" }],
};

//是否展示搜索区域
const showSearchRow = ref(true);
//搜索参数表单
const searchForm = reactive({
  //法规标题
  lawsTitle: null,
  //法规状态
  status: null,
  //页码
  pageNum: 1,
  //条数
  pageSize: 10,
});
//表格选中数据
const selectedKeys = ref([]);
//表格选中
const rowSelection = reactive({
  type: "checkbox",
  showCheckedAll: true,
  onlyCurrent: true,
});
//数据列表
const datatable = reactive({
  //列配置
  columns: [
    {
      title: "法规标题",
      dataIndex: "lawsTitle",
      slotName: "lawsTitle",
      align: "center",
      width: 300,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: "发布时间",
      dataIndex: "publishTime",
      align: "center",
      width: 150,
    },
    {
      title: "法规状态",
      dataIndex: "status",
      slotName: "status",
      align: "center",
      width: 100,
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      align: "center",
      width: 150,
    },
    {
      title: "操作",
      slotName: "operation",
      align: "center",
      width: 160,
      fixed: "right",
    },
  ],
  //加载
  loading: false,
  //数据列表
  records: [],
  //总条数
  total: 0,
});

//查询数据列表
const getPageList = (isReset = false) => {
  if (isReset) {
    searchForm.lawsTitle = null;
    searchForm.status = null;
    searchForm.pageNum = 1;
    searchForm.pageSize = 10;
  }
  datatable.loading = true;

  getPageLawsListApi(searchForm)
    .then((response) => {
      datatable.records = response.records || [];
      datatable.total = response.total || 0;
    })
    .catch((error) => {
      console.error("获取法规列表失败:", error);
      proxy.$msg.error("获取法规列表失败");
    })
    .finally(() => {
      datatable.loading = false;
    });
};

//公共模态框
const modal = reactive({
  //是否显示
  visible: false,
  //模态框标题
  title: "政策法规管理",
  //宽度
  width: "1000px",
  //传递参数
  params: {},
  //组件名称
  component: null,
});

//添加按钮 -> 点击事件
const addBtnClick = () => {
  currentEditLawsId.value = null;
  editorReady.value = false;
  // 重置表单数据
  Object.keys(editForm).forEach((key) => {
    if (key === "status") {
      editForm[key] = 1;
    } else {
      editForm[key] = null;
    }
  });
  // 重置附件文件列表
  lawsFiles.value = [];
  // 重置新上传文件ID跟踪
  newUploadedFileIds.value = [];
  // 清空编辑器内容
  if (editEditorRef.value) {
    editEditorRef.value.setEditorContent("");
  }
  showEditForm.value = true;
};

// 编辑器准备就绪事件
const onEditorReady = () => {
  editorReady.value = true;
  // 如果有待加载的详情数据，现在加载
  if (currentEditLawsId.value) {
    loadLawsDetail(currentEditLawsId.value);
  }
};

// 加载法规详情数据
const loadLawsDetail = (lawsId) => {
  getLawsByLawsIdApi(lawsId)
    .then((response) => {
      const data = response;
      Object.keys(editForm).forEach((key) => {
        if (data.hasOwnProperty(key)) {
          editForm[key] = data[key];
        }
      });

      // 设置附件文件
      lawsFiles.value = data.lawsFiles || [];

      // 设置编辑器内容
      if (editEditorRef.value && data.lawsContent) {
        editEditorRef.value.setEditorContent(data.lawsContent);
      }
    })
    .catch((error) => {
      console.error("获取法规详情失败:", error);
      proxy.$msg.error("获取法规详情失败");
    })
    .finally(() => {
      editSpinLoading.value = false;
    });
};

//编辑按钮 -> 点击事件
const editBtnClick = (lawsId) => {
  currentEditLawsId.value = lawsId;
  editSpinLoading.value = true;
  editorReady.value = false;
  showEditForm.value = true;

  // 如果编辑器已经准备好，直接加载数据
  if (editorReady.value) {
    loadLawsDetail(lawsId);
  }
  // 否则等待编辑器准备好后在onEditorReady中加载
};

// 取消编辑
const cancelEdit = () => {
  // 如果是新增模式且有未保存的文件，清理这些文件
  if (!currentEditLawsId.value) {
    cleanupUnusedFiles();
  }

  showEditForm.value = false;
  currentEditLawsId.value = null;
  editorReady.value = false;
  // 重置表单数据
  Object.keys(editForm).forEach((key) => {
    if (key === "status") {
      editForm[key] = 1;
    } else {
      editForm[key] = null;
    }
  });
  // 重置附件文件列表
  lawsFiles.value = [];
  // 重置新上传文件ID跟踪
  newUploadedFileIds.value = [];
  // 清空编辑器内容
  if (editEditorRef.value) {
    editEditorRef.value.setEditorContent("");
  }
};

// 保存编辑
const saveEdit = () => {
  editFormRef.value.validate((errors) => {
    if (!errors) {
      // 检查富文本编辑器是否已初始化
      if (!editEditorRef.value) {
        proxy.$msg.error("编辑器未初始化，请稍后再试");
        return;
      }

      // 获取富文本编辑器内容
      editForm.lawsContent = editEditorRef.value.getEditorContent();

      // 获取上传的附件ID
      if (editAttachmentUploadRef.value) {
        const attachmentIds = editAttachmentUploadRef.value.getUploadFileId();
        console.log("attachmentIds", attachmentIds);
        editForm.lawsFileId = attachmentIds;
      }

      editSpinLoading.value = true;

      const apiCall = currentEditLawsId.value
        ? updateLawsByLawsIdApi(editForm)
        : addLawsApi(editForm);

      apiCall
        .then((response) => {
          proxy.$msg.success(
            currentEditLawsId.value ? "修改法规成功" : "添加法规成功"
          );
          // 保存成功后清空新上传文件ID跟踪
          newUploadedFileIds.value = [];
          cancelEdit();
          getPageList(false);
        })
        .catch((error) => {
          console.error("保存法规失败:", error);
          proxy.$msg.error("保存法规失败");
        })
        .finally(() => {
          editSpinLoading.value = false;
        });
    }
  });
};

//详情按钮 -> 点击事件
const detailBtnClick = (lawsId) => {
  modal.visible = true;
  modal.title = "法规详情";
  modal.component = shallowRef(LawsDetail);
  modal.params = { lawsId };
};

// 删除确认弹窗
const deleteConfirmVisible = ref(false);

//删除按钮 -> 点击事件
const deleteBtnClick = (keys) => {
  if (!keys || keys.length === 0) {
    proxy.$msg.warning("请选择要删除的数据");
    return;
  }
  deleteConfirmVisible.value = true;
};

//删除确认 -> 取消
const onDeleteConfirmCancel = () => {
  deleteConfirmVisible.value = false;
};

//删除确认 -> 确定
const onDeleteConfirmOK = () => {
  deleteConfirmVisible.value = false;

  const deletePromises = selectedKeys.value.map((lawsId) =>
    deleteLawsByLawsIdApi(lawsId)
  );

  Promise.all(deletePromises)
    .then((responses) => {
      selectedKeys.value = [];
      getPageList(false);
    })
    .catch((error) => {
      console.error("批量删除法规失败:", error);
      proxy.$msg.error("批量删除法规失败");
    });
};

//删除单个 -> 确定
const deleteBtnOkClick = (lawsId) => {
  deleteLawsByLawsIdApi(lawsId)
    .then((response) => {
      proxy.$msg.success("删除法规成功");
      getPageList(false);
    })
    .catch((error) => {
      console.error("删除法规失败:", error);
      proxy.$msg.error("删除法规失败");
    });
};

// 获取状态标签 - 已改用dict-convert组件
// const getStatusLabel = (status) => {
//   const option = dicts[proxy.DICT.commonNumberStatus]?.find((item) => item.dictKey === status);
//   return option ? option.dictValue : "未知";
// };

// 获取状态颜色 - 已改用dict-convert组件
// const getStatusColor = (status) => {
//   const option = dicts[proxy.DICT.commonNumberStatus]?.find((item) => item.dictKey === status);
//   return option ? option.dictClass : "gray";
// };

// 获取文件扩展名
const getFileExtension = (fileName) => {
  if (!fileName) return "";
  const lastDot = fileName.lastIndexOf(".");
  return lastDot !== -1 ? fileName.substring(lastDot + 1).toLowerCase() : "";
};

// 下载附件文件
const downloadAttachmentFile = (file) => {
  if (file.url) {
    const link = document.createElement("a");
    link.href = file.url;
    link.download = file.name || "附件文件";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } else {
    Message.warning("该文件暂无下载链接");
  }
};

// 预览附件文件
const previewAttachmentFile = (file) => {
  if (file.url) {
    window.open(file.url, "_blank");
  } else {
    Message.warning("该文件暂无预览链接");
  }
};

// 复制文件URL
const copyFileUrl = (url) => {
  if (!url) {
    Message.warning("文件URL为空，无法复制");
    return;
  }

  // 使用现代浏览器的Clipboard API
  if (navigator.clipboard && window.isSecureContext) {
    navigator.clipboard
      .writeText(url)
      .then(() => {
        Message.success("文件URL已复制到剪贴板");
      })
      .catch(() => {
        // 降级到传统方法
        fallbackCopyTextToClipboard(url);
      });
  } else {
    // 降级到传统方法
    fallbackCopyTextToClipboard(url);
  }
};

// 降级复制方法
const fallbackCopyTextToClipboard = (text) => {
  const textArea = document.createElement("textarea");
  textArea.value = text;
  textArea.style.top = "0";
  textArea.style.left = "0";
  textArea.style.position = "fixed";
  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();

  try {
    const successful = document.execCommand("copy");
    if (successful) {
      Message.success("文件URL已复制到剪贴板");
    } else {
      Message.error("复制失败，请手动复制");
    }
  } catch (err) {
    Message.error("复制失败，请手动复制");
  }

  document.body.removeChild(textArea);
};

// 删除附件文件
const removeFile = (index) => {
  if (index >= 0 && index < lawsFiles.value.length) {
    const file = lawsFiles.value[index];
    // 如果是新上传的文件，从跟踪列表中移除
    if (file.fileId && newUploadedFileIds.value.includes(file.fileId)) {
      const trackIndex = newUploadedFileIds.value.indexOf(file.fileId);
      if (trackIndex > -1) {
        newUploadedFileIds.value.splice(trackIndex, 1);
      }
    }
    lawsFiles.value.splice(index, 1);
    Message.success("附件已删除");
  }
};

// 处理文件上传成功
const handleUploadSuccess = (response, fileItem, fileList) => {
  console.log("文件上传成功:", response);
  if (response && response.fileId) {
    // 创建文件对象
    const fileObj = {
      fileId: response.fileId,
      name: response.fileName,
      url: response.fileUrl,
      size: response.fileSize,
      type: response.fileType,
    };

    // 添加到文件列表
    lawsFiles.value.push(fileObj);

    // 在新增模式下，跟踪新上传的文件ID
    if (!currentEditLawsId.value) {
      newUploadedFileIds.value.push(response.fileId);
    }

    Message.success("文件上传成功");
  }
};

// 清理未使用的文件
const cleanupUnusedFiles = () => {
  if (newUploadedFileIds.value.length > 0) {
    const deletePromises = newUploadedFileIds.value.map((fileId) => {
      return deleteFileApi(fileId);
    });

    Promise.all(deletePromises)
      .then(() => {
        console.log("已清理未保存的文件:", newUploadedFileIds.value);
        newUploadedFileIds.value = [];
      })
      .catch((error) => {
        console.error("清理未使用文件失败:", error);
        newUploadedFileIds.value = [];
      });
  }
};

//模态框 -> 取消
const onCancel = () => {
  modal.visible = false;
};

//模态框 -> 确定
const onOk = () => {
  modal.visible = false;
  getPageList(false);
};

// 页面加载时获取数据
onMounted(() => {
  getPageList(false);
});
</script>

<style scoped>
/* 样式可以根据需要添加 */
</style>
